package com.scorpio.basic.service.impl;

import java.util.Arrays;
import java.util.List;

import com.scorpio.basic.dto.HomeListResDTO;
import com.scorpio.basic.enums.HomeListRes1SiteEnum;
import com.scorpio.basic.vo.HomeListResVo;
import com.scorpio.common.exception.CustomException;
import org.springframework.stereotype.Service;
import com.scorpio.basic.mapper.HomeListResMapper;
import com.scorpio.basic.domain.HomeListResEntity;
import com.scorpio.basic.service.IHomeListResService;
import com.scorpio.common.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 首页列资源Service业务层处理
 *
 * @author scorpio
 * @date 2021-11-16
 */
@Service
public class HomeListResServiceImpl extends BaseServiceImpl<HomeListResMapper, HomeListResEntity> implements IHomeListResService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HomeListResDTO selectByHomeList(Long hId) {
        initBtHomeList(hId);
        HomeListResDTO dto = new HomeListResDTO();
        dto.style1 = baseDao.selectByHId(hId, HomeListRes1SiteEnum.Top.getType());
        dto.style2 = baseDao.selectByHId(hId, HomeListRes1SiteEnum.BLeft.getType());
        dto.style3 = baseDao.selectByHId(hId, HomeListRes1SiteEnum.BRTop.getType());
        dto.style4 = baseDao.selectByHId(hId, HomeListRes1SiteEnum.BRBottom.getType());
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(HomeListResVo vo) {
        initRes(vo.gethId(), HomeListRes1SiteEnum.Top.getType());
        initRes(vo.gethId(), HomeListRes1SiteEnum.BLeft.getType());
        initRes(vo.gethId(), HomeListRes1SiteEnum.BRTop.getType());
        initRes(vo.gethId(), HomeListRes1SiteEnum.BRBottom.getType());
        int count = baseDao.updateRes(vo.getStyle1());
        count += baseDao.updateRes(vo.getStyle2());
        count += baseDao.updateRes(vo.getStyle3());
        count += baseDao.updateRes(vo.getStyle4());
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initBtHomeList(Long hId) {
        initRes(hId, HomeListRes1SiteEnum.Top.getType());
        initRes(hId, HomeListRes1SiteEnum.BLeft.getType());
        initRes(hId, HomeListRes1SiteEnum.BRTop.getType());
        initRes(hId, HomeListRes1SiteEnum.BRBottom.getType());
    }

    private void initRes(Long hId, String showSite) {
        HomeListResEntity entity = baseDao.selectByHId(hId, showSite);
        if (entity == null) {
            entity = new HomeListResEntity();
            entity.sethId(hId);
            entity.setShowSite(showSite);
            int count = baseDao.insert(entity);
            if (count == 0) {
                throw new CustomException("操作失败");
            }
        }
    }

}
